# coding: utf-8
# @Author: ChuiZi
import logging
import re


def decide(response, condition, describe):
    """pytest框架接口断言判断逻辑

    :param response: request库发送的请求返回值
    :param condition: 用例校验数据
    :param describe: 用例描述
    :return: switch:是否通过测试;res:断言报文
    """
    switch = True
    res = None
    # 大部分编码问题可以通过该方式解决,但是存在可能,接口返回图片或者音频等非文本格式
    response_text = response.content.decode('utf-8')
    if condition == '':
        logging.warning(f'返回值校验数据为空,实际返回值为{response_text}')
        return switch
    for key in condition:
        pattern = fr'"{key}":.+?,"'
        res_reason = re.search(pattern, response_text).group().replace(f"{key}", "")[3:-2].strip(
            '"')  # key值对应的响应数据的txt文本
        if res_reason == 'false': res_reason = False
        if res_reason == 'true': res_reason = True
        if (condition_data := condition.get(key)) != res_reason:
            logging.error('{2}实际值为:"{0}",与预期返回参数"{1}"不相符'.format(res_reason, condition_data, key))
            switch = False
            res = f"{key}的实际值为:{res_reason},预期结果为:{condition_data}"
            break
        # 更加详细的断言需要额外添加逻辑:res_reason是返回结果中与key对应的txt文本,condition.get(key)是校验数据的key值下txt文本
        # 如果返回值校验数据与返回结果全等,那么可以用默认校验来完成,如果不等,那么就需要添加额外校验逻辑
        """
            print(f"{key}对应的返回值文本:,res_reason," ",f"{key}对应的返回值校验数据文本,condition.get(key))
        """
    if switch:
        logging.info('测试场景 "{0}" 通过,实际结果为:{1}'.format(describe, response_text.strip()))
    else:
        logging.error('测试场景 "{0}" 未通过,实际结果为:{1}'.format(describe, response_text.strip()))
    return switch, res
